/**
 */

package com.bei_en.common.util.OSS;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
import org.junit.Before;
import org.junit.Test;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20160224.ImageDetectionRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.gson.Gson;

/**
 * @author Guocg
 *
 */
public class SexSample {

	private IAcsClient client = null;
	private Logger log = Logger.getLogger(this.getClass());

	public SexSample() throws ClientException {

		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
				"uaRj1UVNYFY6rV1V", "uEAQR3pgn1uZLITNwEGozLHIJAkgbm"); // TODO
		DefaultProfile.addEndpoint("oss-cn-shenzhen.aliyuncs.com",
				"cn-shenzhen", "Green", "green.aliyuncs.com");
		client = new DefaultAcsClient(profile);
	}

	/**
	 * 黄图为真
	 * 
	 * @author Guocg
	 * @param url
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	@Test
	public boolean detectImages(String url) {

		ImageDetectionRequest imageDetectionRequest = new ImageDetectionRequest();
		imageDetectionRequest.setProtocol(ProtocolType.HTTP);
		imageDetectionRequest.setAcceptFormat(FormatType.JSON);
		imageDetectionRequest.setContentType(FormatType.JSON);
		imageDetectionRequest.setMethod(MethodType.POST);

		JSONObject keyArg = new JSONObject();
		List<String> imageUrl = new ArrayList<String>();
		// imageUrl.add("http://e.hiphotos.baidu.com/image/h%3D360/sign=fc7d652a4334970a58731629a5cbd1c0/d043ad4bd11373f0d6acc29aa60f4bfbfbed0427.jpg");
		// // TODO
		imageUrl.add(url);
		keyArg.put("image_url", imageUrl);
		List<String> scene = new ArrayList<String>();
		scene.add("porn");
		keyArg.put("scene", scene);
		String content = keyArg.toString();
		imageDetectionRequest.setContent(content.getBytes(), "UTF-8",
				FormatType.JSON);

		try {
			HttpResponse httpResponse = client.doAction(imageDetectionRequest);

			log.info(httpResponse.isSuccess());
			Gson gson = new Gson();
			String jo = new String(httpResponse.getContent());
			log.info(jo);
			SexResp re = gson.fromJson(jo, SexResp.class);
			if (re.getCode().equals("Success")
					&& re.getImages().get(0).getPorn().getLabel() == 1)
				return true;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}